<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.*"%>
<%@ page import="com.google.gdata.client.*"%>
<%@ page import="com.google.gdata.client.http.AuthSubUtil"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<%!/** this function converts an array of cookies into a hashtable */

	Hashtable cookieTable(Cookie[] cookies) {
		Hashtable cookieTable = new Hashtable();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++)
				cookieTable.put(cookies[i].getName(), cookies[i].getValue());
		}
		return cookieTable;
	}
	
%>
<%! Boolean bIsTokenCookie = false; %>
<%! String cToken=null; %>
<%
try
{
	response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
	response.setHeader("Pragma","no-cache"); //HTTP 1.0
	response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
	
	response.addHeader("P3P","CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"");
	
	Cookie myCookie;
	
	String cNewToken = request.getParameter("token");
	String cDoLogin = request.getParameter("login");
	String cDoLogout = request.getParameter("logout");
		String cUrl = request.getParameter("cUrl");

	if (cDoLogout!=null)
	{
		myCookie = new Cookie("tokenmemoryofaplace", "");
		myCookie.setMaxAge(0);
		cToken = null;
		response.addCookie(myCookie);
	}
	else
	{	
	
	Hashtable cookies = cookieTable(request.getCookies());
	
	if (cookies.containsKey("tokenmemoryofaplace")) {		
		cToken = (String) cookies.get("tokenmemoryofaplace");
		bIsTokenCookie = true;
	}
	if (cNewToken != null) {
		if (cNewToken.equals("")) {
			myCookie = new Cookie("tokenmemoryofaplace", "");
			myCookie.setMaxAge(0);
			cToken = null;
			response.addCookie(myCookie);
		} else {
			if (!bIsTokenCookie)
			{	
				// Convert the unique token in session token
				cToken = AuthSubUtil.exchangeForSessionToken(cNewToken,	null);
				myCookie = new Cookie("tokenmemoryofaplace", cToken);
				myCookie.setMaxAge(3600);
				response.addCookie(myCookie);
				bIsTokenCookie = true;
			}
		}
		if (cUrl!=null && cUrl!="")
			response.sendRedirect(cUrl);
	}
	if (cDoLogin != null) {
		
		if ((cToken == null) || (cToken == "")) {
			String nextUrl = request.getRequestURL().toString();
			String scope = "http://gdata.youtube.com";
			boolean lSecure = false; // set secure=true to request secure AuthSub tokens
			boolean lSession = true;
			String authSubUrl = AuthSubUtil.getRequestUrl(nextUrl,
					scope, lSecure, lSession);
			response.sendRedirect(authSubUrl);
		}
	}
	}
}
catch (Exception e)
{
	
}
%>

<html>
    <%
    Locale l = request.getLocale();
    %>

    <c:choose> 
        <c:when test="${!(empty param.locale)}"> 
            <c:set var="loc" value="${param.locale}"/>
        </c:when> 
        <c:otherwise> 
            <c:set var="loc" value="<%=l%>"/>
        </c:otherwise> 
    </c:choose> 

    <fmt:setLocale value="${loc}" />
    <fmt:bundle basename="messages">
        <head>
            <title><fmt:message key="appTitle"/></title>
            <link rel="stylesheet" href="./css/index.css" type="text/css" />
            <script type="text/javascript" src="./js/jquery-1.5.1.min.js"></script>
            <script type="text/javascript" src="./js/jquery.cookie.js"></script>
            <script type="text/javascript" src="./js/functions.js"></script>
            <script src="https://www.google.com/jsapi?key=ABQIAAAAJJNfvQzdCsbpXc0cNOgTaRSuuZWYEDeEvw57ZlCQT3r8MoHXtBQ0Xwjf8UYMaroiT0q1sBBkTdze-g" type="text/javascript"></script>
            <script language="javascript">
            var cleanUrl = "${pageContext.request.requestURL}";
            
            function doLogin()
            {
            	 document.location.href = cleanUrl + "?login=1";
            }
            
            function doLogout()
            {
           	 	document.location.href = cleanUrl + "?logout=1";            
            }

            
            function uploadVideo()
            {
            	$("#uploadStatus").text("uploading video to place....");
            	$.post("/rpc", {
            		action : "addPlaceMedia",
            		arg0 :  $("#codPlace").val(),
            		arg1 :  $("#videoUrl").val(),
            		arg2 :  $("#videoThumbnail").val(),
            		arg3 :  $("#videoTitle").val(),
            		arg4 :  $("#videoDescription").val(),
            		arg5 :  $("#mediaType").val(),
            		arg6 :  2,
            		arg7 :  $("#taken").val()            		
            	}, onUploadVideoSuccess);
            	
            }
            
            function onUploadVideoSuccess(response)
            {
            	if (response == null) {
            		$("#uploadStatus").text("No se ha obtenido respuesta");
            		return;
            	}
            	else
            	{
            		$("#uploadStatus").text(JSON.stringify(response));               		           		
            	}
            }
            function getVideos()
            {
            	$("#resultado").text("*** cargando datos");
            	$.post("/auth", {
            		action : "getVideos",
            		token : $.cookie('tokenmemoryofaplace')
            	}, onGetVideosSuccess);
            }

            function onGetVideosSuccess(response)
            {
            	if (response == null) {
            		$("#resultado").text("No se ha obtenido respuesta");
            		return;
            	}
            	else
            	{
            	       		           		
            		var username =  response.feed.author[0].name.$t;
            		$("#videoUser").val(username);
            		if (response.feed.entry!=undefined){
        		 		$.each(response.feed.entry,function(i,videos){
        		 			if (videos.media$group.yt$private==undefined){
        		 				$("#resultado").append("<img id='placeVideo" + i + "' src='" + videos.media$group.media$thumbnail[0].url.split("/0.jpg").join("/1.jpg") + "'/>");
        		 				var video_thumbnail = videos.media$group.media$thumbnail[0].url;
        		 				var video_url = videos.link[0].href;
        		 				var video_title =  videos.media$group.media$title.$t;
        		 				var video_description = videos.media$group.media$description.$t;
        		 				$("#placeVideo" + i).data("thumbnail",video_thumbnail);
        		 				$("#placeVideo" + i).data("url",video_url);
        		 				$("#placeVideo" + i).data("title",video_title);
        		 				$("#placeVideo" + i).data("description",video_description);
        		 				$("#placeVideo" + i).click(function(event) {
        		 					var oTarget = $("#" + event.target.id);
        		 					$("#videoTitle").val(oTarget.data("title"));
        		 					$("#videoDescription").val(oTarget.data("description"));
        		 					$("#videoUrl").val(oTarget.data("url"));
        		 					$("#videoThumbnail").val(oTarget.data("thumbnail"));
        		 				  });
        		 			}
        		 		})	
            		}
            	}
            }

            
			google.load('gdata', '2.x');
			google.setOnLoadCallback(checkToken);
            </script>
        </head>
        <body>
            <h1><fmt:message key="appTitle"/></h1>

            <% if (cToken==null) { %>            
Not authenticate
<br/>
<button name="submit_button" id="submit_button" style="padding:5px;margin-top:20px;" onclick="doLogin()">
<img src="http://www.google.com/favicon.ico" alt="Sign in with a Google Account" style="margin-bottom:-3px;">&nbsp; Sign in using your Google Account
</button>
<% } else { %>        
Authenticate OK
<br/>
<script>
getVideos();
</script>
<div id="resultado" style="background-color:#babada;width:720px;height:170px;overflow:auto;font-size:small;padding:2px"></div>


User: <input type="text" id="videoUser" /><br/>
Place Code: <input type="text" id="codPlace" value="6002" /><br/>
Taken: <input type="text" id="taken" value="1998" />
<select id="mediaType">
<option value="1">BEFORE</option>
<option value="2">AFTER</option>
<option value="3">NOW</option>
</select><br/>
<br/>
Title: <input type="text" id="videoTitle" /><br/>
Description: <input type="text" id="videoDescription" /><br/>
Url: <input type="text" id="videoUrl" style="width:400px"/><br/>	
Thumbnail: <input type="text" id="videoThumbnail" style="width:400px"/><br/>
<button id="uploadVideo" style="padding:5px;margin-top:20px;" onclick="uploadVideo()">
Upload Video to Place
</button>
<div id="uploadStatus"></div><br/>

<button  id="submit_button" style="padding:5px;margin-top:20px;" onclick="doLogout()">
<img src="http://www.google.com/favicon.ico" alt="Sign out Google Account" style="margin-bottom:-3px;">&nbsp; Sign out Google Account
</button>

<% } %>
<script>
console.log("Checktoken:" + checkToken());
console.log("prueba <%=bIsTokenCookie%>");
console.log("cToken <%=cToken%>");

</script>


 </body>
    </fmt:bundle>
</html>










